<?php
/*
+-----------------------------------------------------------------------------+
| $Id: install.php 2010-05-24 03:05:27Z Bleakwind $
| System Install
| Copyright (c) 2003-2010 Bleakwind (www.weaverdream.com)
| http://www.weaverdream.com/
| Release under the GNU Lesser General Public License Version 3 (LGPLv3):
|   http://www.gnu.org/licenses/lgpl.html
+-----------------------------------------------------------------------------+
*/

// Set file
$set['file_name']   = "./upgrade1.0to1.1.php";
$set['file_htm']    = "./upgrade1.0to1.1.htm";
$set['file_sql']    = "./upgrade1.0to1.1.mysql.sql";
$set['title']       = "程序升级 (1.0 &raquo; 1.1)";
$set['title_menu']  = "升级进度";
$set['warn_input']  = "";
$set['version']     = "1.1";

// Set envionment variables
@set_time_limit(0);
@error_reporting(E_ALL ^ E_NOTICE);
@set_magic_quotes_runtime(0);
session_name("install_firmkernel_sessid");
session_start();

// Initialize
// Include all public files
include_once '../config.php';

include_once '../lib/adodb/adodb.inc.php';
include_once '../lib/smarty/Smarty.class.php';
include_once '../lib/function.php';

// Include all private files
include_once '../source/lib/sys.class.php';
include_once '../source/configure.php';

// Start the sys
$sys = new sys();

// Parse URL
$page_http              = $_SERVER['HTTPS'] == "on" ? "https://" : "http://";
$page_server_name       = $_SERVER['SERVER_NAME'];
$page_ports             = $_SERVER['SERVER_PORT'] != "80" ? ":".$_SERVER['SERVER_PORT'] : "";
$PAGE_PATH['rootdir']   = $page_http.$page_server_name.$page_ports.substr($_SERVER['SCRIPT_NAME'],0,strrpos($_SERVER['SCRIPT_NAME'],'/')-7);

// Set default timezone
date_default_timezone_set($CONFIG['default_timezone']);
// Set encoding for multibyte regex
mb_regex_encoding("UTF-8");

// Initialize db
$ADODB_CACHE_DIR = "./cache/adodb/";
if (!file_exists($ADODB_CACHE_DIR)) { func::make_dir($ADODB_CACHE_DIR); }
$db = &ADONewConnection(CONFIG_DB_TYPE);

// Get the Language
$LANGLIST[1]['id']    = "1";
$LANGLIST[1]['name']  = "Chinese simplified";
$LANGLIST[1]['code']  = "cn";
$LANGLIST[1]['icon']  = "icon.png";
$LANGLIST[1]['dir']   = "chinese_simplified";
$LANGLIST[1]['rank']  = "1";

// Get the Template
$TEMPLATE[1]['id']    = "1";
$TEMPLATE[1]['name']  = "Default";
$TEMPLATE[1]['dir']   = "default";
$TEMPLATE[1]['rank']  = "1";

// Set Default
$CONFIG['language'] = "1";
$CONFIG['template'] = "1";

// Include Language
include_once '../language/'.$LANGLIST[$CONFIG['language']]['dir'].'/source/_public.php';
include_once '../language/'.$LANGLIST[$CONFIG['language']]['dir'].'/template/_public.php';

// Start the Template
$compile_dir = "./cache/compile/";
$cache_dir   = "./cache/cache/";
if (!file_exists($compile_dir)) { func::make_dir($compile_dir); }
if (!file_exists($cache_dir))   { func::make_dir($cache_dir); }
$t = new Smarty();
include_once '../lib/function.smarty.php';
$t->template_dir   = "./";
$t->compile_dir    = $compile_dir;
$t->cache_dir      = $cache_dir;
$t->compile_check  = true;
$t->cache_lifetime = 60;
//$t->caching        = true;
//$t->debugging      = true;

// Start Ajax
if (is_file("../lib/xajax/xajax_core/xajaxAIO.inc.php")) {
    include_once '../lib/xajax/xajax_core/xajaxAIO.inc.php';
} elseif (is_file("../lib/xajax/xajax_core/xajax.inc.php")) {
    include_once '../lib/xajax/xajax_core/xajax.inc.php';
} else {
    echo "Error load Xajax module!";
    exit;
}
$bwajax = new xajax();
//$bwajax->configure('debug',true);
$bwajax->configure('statusMessages',true);
$bwajax->configure('javascript URI', '../lib/xajax/');
include_once '../lib/function.ajax.php';

// Include Setting
include_once '../source/setting.php';

$t->assign(array(
    "set"   => $set,
));

/************************************ Config **********************************/

$check_dir = array(
                "../config.php",
                "../cache",
                "../build",
                "../upload",
                "../upload/channel_cover",
                "../upload/content_cover",
                "../upload/content_attach",
                "../upload/article_cover",
                "../upload/article_attach",
                "../upload/datum_cover",
                "../upload/datum_attach",
                "../upload/upload_tmp",
                "../upload/member_avatar",
                "../upload/userfiles",
                "../admin/cache",
                "../install",
             );
$install['introduction'] = '　　1. 本软件是由 <a href="http://www.weaverdream.com/" target="_blank">Weaverdream</a> 开发制作的 Firmkernel网站内容管理系统. <br />　　2. Firmkernel采用PHP开发. <br />　　3. 您可以从 <a href="http://www.weaverdream.com/" target="_blank">www.weaverdream.com</a> 获取该软件. <br />　　4. 您使用本软件所产生的任何事情 Weaverdream 均不承担任何责任和义务. <br />　　5. 如需更多关于 Weaverdream, Firmkernel 的信息请访问 <a href="http://www.weaverdream.com/" target="_blank">www.weaverdream.com</a>.';
$install['rule'] = '　　Firmkernel'.$set['version'].' 是基于 <a href="http://www.gnu.org/licenses/gpl.html" target="_blank">GNU GENERAL PUBLIC LICENSE Version 3(GPLv3)</a> 授权协议的软件.';
/************************************ Function **********************************/
function check_agree(){
    global $check_dir;
    $result = "1";
    if ($_SESSION['install_firmkernel_agree'] != "1") {
        $result = "2";
    }
    return $result;
}
function check_dir(){
    global $check_dir;
    $result = "1";
    foreach ($check_dir as $v){
        if (!is_writable($v)) {
            $result = "2";
        }
    }
    return $result;
}
function agree_rule($value)
{
    global $SETTING,$LANGUAGE,$CONFIG,$CONFIGURE,$PROMPT,$LANGLIST,$db,$sys,$c;
    $ajax_response = new xajaxResponse();
    $button = "button_agree";
    $error = false;
    //$ajax_response->alert(print_r($value, true)); $ajax_response->assign($submit,"disabled",false); return $ajax_response;
    //func::fp($value);

    if ( $value['agree'] != "1" ) {
        $error = true;
        $ajax_response->assign("agree_return", "innerHTML", "<span class=\"prompt_failed\">您必须同意Firmkernel授权协议才能继续安装!</span>");
    }else{
        $ajax_response->assign("agree_return", "innerHTML", "");
    }

    if($error){
        $ajax_response->assign($button,"value", "下一步");
        $ajax_response->assign($button,"disabled",false);
    }else{
        $_SESSION['install_firmkernel_agree']            = $value['agree'];
        $ajax_response->redirect($set['file_name']."?act=check");
    }
    return $ajax_response;
}
$bwajax->register(XAJAX_FUNCTION, "agree_rule");
function input_msg($value)
{
    global $SETTING,$LANGUAGE,$CONFIG,$CONFIGURE,$PROMPT,$LANGLIST,$db,$sys,$c;
    $ajax_response = new xajaxResponse();
    $button = "button_input";
    $error = false;
    //$ajax_response->alert(print_r($value, true)); $ajax_response->assign($submit,"disabled",false); return $ajax_response;
    //func::fp($value);

    if ( !preg_match("/^[a-z0-9_]{1,20}$/i",$value['site_cookie_prefix']) ) {
        $error = true;
        if(empty($anchor)) { $anchor = "site_cookie_prefix"; }
        $ajax_response->assign("site_cookie_prefix_return", "innerHTML", "<span class=\"prompt_failed\">Cookies前缀不符合规范,1-10字节,英文,数字或下划线!</span>");
    }else{
        $ajax_response->assign("site_cookie_prefix_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
    }

    $result_connect = @$db->NConnect($value['db_host'], $value['db_user'], $value['db_pass'], $value['db_database']);
    if (!$result_connect) {
        $error = true;
        if(empty($anchor)) { $anchor = "db_host"; }
        $ajax_response->assign("db_host_return", "innerHTML", "<span class=\"prompt_failed\">无法连接数据库,请仔细检查数据库主机地址!</span>");
        $ajax_response->assign("db_user_return", "innerHTML", "<span class=\"prompt_failed\">无法连接数据库,请仔细检查数据库连接用户名!</span>");
        $ajax_response->assign("db_pass_return", "innerHTML", "<span class=\"prompt_failed\">无法连接数据库,请仔细检查数据库连接密码!</span>");
        $ajax_response->assign("db_database_return", "innerHTML", "<span class=\"prompt_failed\">无法连接数据库,请仔细检查数据库是否存在,不存在请先建立数据库!</span>");
    } else {
        $ajax_response->assign("db_host_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
        $ajax_response->assign("db_user_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
        $ajax_response->assign("db_pass_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
        $ajax_response->assign("db_database_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
    }

    if ( !preg_match("/^[a-z0-9_]{1,10}$/i",$value['db_prefix']) ) {
        $error = true;
        if(empty($anchor)) { $anchor = "db_prefix"; }
        $ajax_response->assign("db_prefix_return", "innerHTML", "<span class=\"prompt_failed\">数据库表前缀不符合规范,1-10字节,英文,数字或下划线!</span>");
    }else{
        $ajax_response->assign("db_prefix_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
    }

    if($error){
        $ajax_response->assign($button,"value", "下一步");
        $ajax_response->assign($button,"disabled",false);
        $ajax_response->redirect("#".$anchor);
    }else{
        $_SESSION['install_firmkernel_db_host']            = $value['db_host'];
        $_SESSION['install_firmkernel_db_user']            = $value['db_user'];
        $_SESSION['install_firmkernel_db_pass']            = $value['db_pass'];
        $_SESSION['install_firmkernel_db_database']        = $value['db_database'];
        $_SESSION['install_firmkernel_db_prefix']          = $value['db_prefix'];
        $_SESSION['install_firmkernel_site_root']          = $value['site_root'];
        $_SESSION['install_firmkernel_site_root_admin']    = $value['site_root_admin'];
        $_SESSION['install_firmkernel_site_cookie_prefix'] = $value['site_cookie_prefix'];
        $ajax_response->redirect($set['file_name']."?act=install");
    }
    return $ajax_response;
}
$bwajax->register(XAJAX_FUNCTION, "input_msg");

/************************************ Install **********************************/
$install_lock = "2";
if (is_file("./install.lock") && $sys->get['act'] != "finish") {
    $install_lock = "1";
} else {
    if ($sys->get['act'] == "check"){
        foreach ($check_dir as $v){
            if (!@chmod($v, $SETTING['chmod_mode_file'])) {
                @chmod($v, "0777");
            }
        }
        $result_agree       = check_agree();
        $result_check_dir   = check_dir();
        if ($result_agree != "1") {
            @header("Location: ".$set['file_name']);
        } elseif ($result_check_dir == "1") {
            @header("Location: ".$set['file_name']."?act=input");
        }
        $t->assign("result_check_dir", $result_check_dir);

    } elseif ($sys->get['act'] == "input"){
        $result_agree       = check_agree();
        $result_check_dir   = check_dir();
        if ($result_agree != "1") {
            @header("Location: ".$set['file_name']);
        } elseif ($result_check_dir != "1") {
            @header("Location: ".$set['file_name']."?act=check");
        }

    } elseif ($sys->get['act'] == "install"){
        $result_agree       = check_agree();
        $result_check_dir   = check_dir();
        if ($result_agree != "1") {
            @header("Location: ".$set['file_name']);
        } elseif ($result_check_dir != "1") {
            @header("Location: ".$set['file_name']."?act=check");
        }

        $result_connect = @$db->NConnect($_SESSION['install_firmkernel_db_host'], $_SESSION['install_firmkernel_db_user'], $_SESSION['install_firmkernel_db_pass'], $_SESSION['install_firmkernel_db_database']);
        if (!$result_connect) {
            @header("Location: ".$set['file_name']."?act=input");
        }
        $db->Execute("SET NAMES '".CONFIG_DB_CHARSET."'");
        $content_config = func::read_file("../config.php");
        $content_config = trim($content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_ROOT[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_ROOT',                       '".$_SESSION['install_firmkernel_site_root']."');", $content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_ROOT_ADMIN[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_ROOT_ADMIN',                 '".$_SESSION['install_firmkernel_site_root_admin']."');", $content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_COOKIE_PREFIX[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_COOKIE_PREFIX',              '".$_SESSION['install_firmkernel_site_cookie_prefix']."');", $content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_DB_HOSTNAME[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_DB_HOSTNAME',                '".$_SESSION['install_firmkernel_db_host']."');", $content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_DB_USERNAME[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_DB_USERNAME',                '".$_SESSION['install_firmkernel_db_user']."');", $content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_DB_PASSWORD[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_DB_PASSWORD',                '".$_SESSION['install_firmkernel_db_pass']."');", $content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_DB_DATABASE[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_DB_DATABASE',                '".$_SESSION['install_firmkernel_db_database']."');", $content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_DB_PREFIX[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_DB_PREFIX',                  '".$_SESSION['install_firmkernel_db_prefix']."');", $content_config);

        $content_sql = func::read_file($set['file_sql']);
        $content_sql = trim($content_sql);
        if ($_SESSION['install_firmkernel_db_prefix'] != "fk_") {
            $content_sql = preg_replace("/CREATE TABLE IF NOT EXISTS `fk_/i", "CREATE TABLE IF NOT EXISTS `".$_SESSION['install_firmkernel_db_prefix']."", $content_sql);
        }
        $content_sql = preg_replace("/\n--[^\n]*/i", "", $content_sql);
        $content_sql = preg_replace("/\/\*.*?\*\/\;\n?/i", "", $content_sql);
        $content_sql = preg_replace("/DROP TABLE IF EXISTS/", "WEAVERDREAM_FIRMKERNEL_DATABASE_SEPARATOR DROP TABLE IF EXISTS", $content_sql);
        $content_sql = preg_replace("/CREATE TABLE IF NOT EXISTS/", "WEAVERDREAM_FIRMKERNEL_DATABASE_SEPARATOR CREATE TABLE IF NOT EXISTS", $content_sql);
        $content_sql = preg_replace("/INSERT INTO/", "WEAVERDREAM_FIRMKERNEL_DATABASE_SEPARATOR INSERT INTO", $content_sql);
        $content_sql = preg_replace("/ALTER TABLE/", "WEAVERDREAM_FIRMKERNEL_DATABASE_SEPARATOR ALTER TABLE", $content_sql);
        $content_sql = preg_replace("/UPDATE/", "WEAVERDREAM_FIRMKERNEL_DATABASE_SEPARATOR UPDATE", $content_sql);
        $content_sql = preg_replace("/TRUNCATE/", "WEAVERDREAM_FIRMKERNEL_DATABASE_SEPARATOR TRUNCATE", $content_sql);
        $content_sql = explode("WEAVERDREAM_FIRMKERNEL_DATABASE_SEPARATOR", $content_sql);

        $result_install_config  = "1";
        $result_install_sql     = "1";

        if (!func::write_file("../config.php", $content_config)){
            $result_install_config = "2";
        }

        foreach($content_sql as $v){
            $v = trim($v);
            if (!empty($v)) {
                $result = &$db->Execute($v);
                if (!$result) {
                    $result_install_sql = "2";
                }
            }
        }

        if ($result_install_config == "1" && $result_install_sql == "1") {
            func::write_file("./install.lock", "Locked By Weaverdream...");
            @chmod("./install.lock", $SETTING['chmod_mode_file']);
            @header("Location: ".$set['file_name']."?act=finish");
        }

        $t->assign("result_install_config", $result_install_config);
        $t->assign("result_install_sql", $result_install_sql);

    } elseif ($sys->get['act'] == "finish"){
        unset($_SESSION);
    } elseif ($sys->get['act'] == "lisense"){
        unset($_SESSION);
    } else {

    }

}

/************************************ End **********************************/
// Other parse
$t->assign("install_lock", $install_lock);
$t->assign("check_dir", $check_dir);
$t->assign("page_path", $PAGE_PATH);
$t->assign("install", $install);
$t->assign("_session", $_SESSION);
$t->assign("get", $sys->get);
$t->assign("post", $sys->post);
$t->assign("langlist", $LANGLIST);
$t->assign("lang", $LANGUAGE);
$t->assign($public_var);
// Xajax
$bwajax->processRequest();
$bwajax_printJavascript = $bwajax->getJavascript();
$t->assign(array(
    "bwajax_printJavascript"    => $bwajax_printJavascript,
));
// Print page
$t->display($set['file_htm']);
?>